<template>
    <div id="RegisterLog">
        <div class="animationBackground">
            <div class="panelBox">
                <!-- 左侧轮播图片展示区 -->
                <div class="panelBox-carouselBox">
                    <div
                        class="panelBox-carouselItem"
                        :class="{ 'panelBox-carouselActiveItem' : activeCarouselItem === index }"
                        v-for="(imgItem, index) in carouselImgList"
                        :key="'carouseImg' + index"
                    >
                        <img :src="imgItem" alt="">
                    </div>
                </div>

                <!-- 右侧表单栏 -->
                <div class="panelBox-contentBox">
                    <h3 class="panelBox-contentBox-title">{{ title }}</h3>

                    <div class="panelBox-contentBox-userImgBox">
                        <img src="../../../assets/images/userImg.jpg" alt="">
                    </div>

                    <div class="panelBox-contentBox-switchBox">
                    <span
                        @click="changeActiveFormBox('logBox')"
                        class="panelBox-contentBox-switchBox-item"
                        :class="{ 'panelBox-contentBox-switchBox-activeItem' : activeFormBox === 'logBox' }"
                    >
                        登陆
                    </span>
                        <span class="panelBox-contentBox-switchBox-separate">/</span>
                        <span
                            @click="changeActiveFormBox('registerBox')"
                            class="panelBox-contentBox-switchBox-item"
                            :class="{ 'panelBox-contentBox-switchBox-activeItem' : activeFormBox === 'registerBox' }"
                        >
                        注册
                    </span>
                    </div>

                    <div class="panelBox-contentBox-formBox">
                        <!-- 登陆 -->
                        <div
                            class="panelBox-contentBox-formBox-item"
                            :class="{ 'panelBox-contentBox-formBox-activeItem' : activeFormBox === 'logBox' }"
                        >
                            <div class="input-textItem">
                                <i class="fa fa-user-o"></i>

                                <label for="userName-log"></label>
                                <input id="userName-log" type="text" placeholder="用户名" required>
                            </div>

                            <div class="input-textItem">
                                <i class="fa fa-key"></i>

                                <label
                                    for="password-log"
                                    data-status="false"
                                    @click="changeLookPasswordStatus($event)"
                                    class="fa fa-eye input-lookPassword"
                                ></label>
                                <input
                                    id="password-log"
                                    type="password"
                                    placeholder="密码"
                                    required
                                    minlength="8" maxlength="32"
                                >
                            </div>

                            <div class="input-toolBox">
                                <div class="input-toolBox-forgetPassword">
                                    <span @click="changeActiveFormBox('forgetPasswordBox')">忘记密码?</span>
                                </div>
                            </div>

                            <SliderSwitchButton
                                buttonContent="登陆"
                            />
                        </div>

                        <!-- 注册 -->
                        <div
                            class="panelBox-contentBox-formBox-item"
                            :class="{ 'panelBox-contentBox-formBox-activeItem' : activeFormBox === 'registerBox' }"
                        >
                            <div class="input-textItem">
                                <i class="fa fa-user-o"></i>

                                <label for="userName-register"></label>
                                <input id="userName-register" type="text" placeholder="用户名" required>
                            </div>

                            <div class="input-textItem">
                                <i class="fa fa-key"></i>

                                <label
                                    for="password-register"
                                    data-status="false"
                                    @click="changeLookPasswordStatus($event)"
                                    class="fa fa-eye input-lookPassword"
                                ></label>
                                <input
                                    id="password-register"
                                    type="password"
                                    placeholder="密码"
                                    required
                                    minlength="8" maxlength="32"
                                >
                            </div>

                            <div class="input-textItem">
                                <i class="fa fa-key"></i>

                                <label
                                    for="repeatPassword-register"
                                    data-status="false"
                                    @click="changeLookPasswordStatus($event)"
                                    class="fa fa-eye input-lookPassword"
                                ></label>
                                <input
                                    id="repeatPassword-register"
                                    type="password"
                                    placeholder="重复密码"
                                    required
                                    minlength="8" maxlength="32"
                                >
                            </div>

                            <div class="input-textItem">
                                <i class="fa fa-exchange"></i>

                                <label for="verify-register"></label>
                                <input id="verify-register" type="text" placeholder="验证码" required>
                            </div>

                            <SliderSwitchButton
                                buttonContent="注册"
                            />
                        </div>

                        <!-- 找回密码 -->
                        <div
                            class="panelBox-contentBox-formBox-item"
                            :class="{ 'panelBox-contentBox-formBox-activeItem' : activeFormBox === 'forgetPasswordBox' }"
                        >
                            <div class="input-textItem">
                                <i class="fa fa-user-o"></i>

                                <label for="userName-forgetPassword"></label>
                                <input id="userName-forgetPassword" type="text" placeholder="用户名" required>
                            </div>

                            <div class="input-textItem">
                                <i class="fa fa-envelope-o"></i>

                                <label for="Email-forgetPassword"></label>
                                <input id="Email-forgetPassword" type="email" placeholder="E-mail" required>
                            </div>

                            <div class="input-textItem">
                                <i class="fa fa-exchange"></i>

                                <label for="verify-forgetPassword"></label>
                                <input id="verify-forgetPassword" type="text" placeholder="验证码" required>
                            </div>

                            <SliderSwitchButton
                                buttonContent="找回密码"
                                buttonIconType="fa-search"
                            />
                        </div>
                    </div>
                </div>
            </div>

            <!-- 底部浮动版权信息栏 -->
            <CopyrightBox/>
        </div>
    </div>
</template>

<script>
    import Axios from 'axios';
    import MD5 from 'js-md5';
    import CopyrightBox from "../components/CopyrightBox.vue"
    import SliderSwitchButton from "../components/SliderSwitchButton.vue"

    /**
     * @file RegisterLog.vue
     * @description 注册登陆组件
     * @vue-prop {String} questionContent - 传入提问问题
     * @vue-data {String} title - 网站名，用于替代Logo
     * @vue-data {Array} randomKeyList - 随机密文插入位列表
     * @vue-event {Function} getRandomKey - 获取密文插入位列表
     * @module RegisterLog
     */
    export default {
        name: "RegisterLog",
        components: {
            CopyrightBox,
            SliderSwitchButton
        },
        data() {
            return {
                title: 'TBJIE',
                // userPassword: '',
                activeCarouselItem: 0,
                activeFormBox: 'logBox',
                carouselImgList: [
                    require('../../../assets/images/carouselImg1.jpg'),
                    require('../../../assets/images/carouselImg2.jpg'),
                    require('../../../assets/images/carouselImg3.jpg'),
                    require('../../../assets/images/carouselImg4.jpg'),
                ],
                registeredDataObject: {},
                logDataObject: {},
            }
        },
        methods: {
            /* 样式函数 */
            nextCarouseItem() {
                if (this.activeCarouselItem === this.carouselImgList.length - 1) {
                    // 最后一张图片
                    this.activeCarouselItem = 0;
                } else {
                    // 不是最后一张图片
                    this.activeCarouselItem++;
                }
            },
            carouseTimer(time = 8000) {
                setInterval(() => {
                    this.nextCarouseItem()
                }, time);
            },
            changeActiveFormBox(activeFormBox) {
                this.activeFormBox = activeFormBox;
            },
            changeLookPasswordStatus(e) {
                // e.target 获取当前点击元素
                // e.currentTarget.previousElementSibling 获取当前点击元素的前一个兄弟元素
                // e.currentTarget.nextElementSibling 获取当前点击元素的后一个兄弟元素
                // 变更关联 label 动态样式类
                if (e.target.getAttribute("data-status") === 'true') {
                    e.target.setAttribute("data-status","false");
                    e.target.classList.remove("input-onLookPassword");
                } else {
                    e.target.setAttribute("data-status","true");
                    e.target.classList.add("input-onLookPassword");
                }
                // 更改输入框类型
                if (String( e.currentTarget.nextElementSibling.type ) === 'text') {
                    e.currentTarget.nextElementSibling.type = "password";
                } else {
                    e.currentTarget.nextElementSibling.type = "text";
                }
            },
            /* 接口函数 */
            getRandomKeyAndKeySaltToRegistered(password, userName) {
                let that = this;

                Axios.post(
                    'http://xxx.com/xxx/xxx',
                    {
                        // 请求随机插入位与盐
                        code: 0,
                        msg: '请求randomKey',
                        data: {
                            passwordDigits: password.length,
                            peopleName: userName
                        },
                        isSuccess: false
                    }
                ).then(resp => {
                    // 承接接口回文数据
                    // {
                    //     "data": {
                    //          "randomKey": 加盐随机位数组，数组格式数据，内含Number数据格式数据,
                    //          "keySalt": 用户对应的盐
                    //      },
                    //     "msg": "已成功返回randomKey",
                    //     "code": 200,
                    //     "isSuccess": true
                    // }
                    that.registeredDataObject.randomKeyList = resp.data.randomKey;
                    that.registeredDataObject.keySalt = resp.data.keySalt;
                }).catch(err => {
                    // 失败执行
                    console.log(err);
                    // console.log('请求失败：' + err.status + ',' + err.statusText)
                })
            },
            postCiphertextToRegistered(password, userName) {
                let that = this;

                let passwordMD5 = that.encrypt(
                    password,
                    that.registeredDataObject.keySalt,
                    that.registeredDataObject.randomKeyList
                );

                Axios.post(
                    'http://xxx.com/xxx/xxx',
                    {
                        // 注册用户，并获取返回的 token 和 peopleId
                        code: 0,
                        msg: '用户注册',
                        data: {
                            passwordMD5: passwordMD5,
                            peopleName: userName,
                            verificationCode: ''    // 验证码，暂时留空
                        },
                        isSuccess: false
                    }
                ).then(resp => {
                    // 承接接口回文数据
                    // {
                    //     "data": {
                    //          "token": token 令牌,
                    //          "peopleId": 用户id
                    //      },
                    //     "msg": "已成功注册",
                    //     "code": 200,
                    //     "isSuccess": true
                    // }
                    // 将 userId 和 token 存入 cookie, 该 cookie path 设为 /forum
                    let forumTokenCookie = {
                        token: resp.data.token,
                        peopleId: resp.data.peopleId
                    };
                    this.$jsCookie.set('forumTokenCookie', forumTokenCookie, { expires: 3, path: 'forum' });

                }).catch(err => {
                    // 失败执行
                    console.log(err);
                    // console.log('请求失败：' + err.status + ',' + err.statusText)
                })
            },
            getRandomKeyAndKeySaltToLog(userName) {
                let that = this;

                Axios.post(
                    'http://xxx.com/xxx/xxx',
                    {
                        // 请求随机插入位与盐
                        code: 0,
                        msg: '用户登陆',
                        data: {
                            peopleName: userName
                        },
                        isSuccess: false
                    }
                ).then(resp => {
                    // 承接接口回文数据
                    // {
                    //     "data": {
                    //         "oldRandomKey": [1, 3, 16, 68, 0, 25, 110],
                    //         "newRandomKey": [1, 5, 11, 58, 33, 13, 69],
                    //         "oldKeySalt" : 旧的128位盐值,
                    //         "newKeySalt" : 新的128位盐值,
                    //         "peopelId" : 1,
                    //     },
                    //     "msg": "已返回新旧randomKey",
                    //     "code": 200,
                    //     "isSuccess": true
                    // }
                    // 利用这些数据进行加密，
                    // 然后利用oldRandomKey长度和用户输入密码位数进行对比，若为通过说明密码错误，
                    // 若对比通过则重复注册时的加密过程生成新旧两个passwordMD5，最后将这些返回给后端
                    that.logDataObject.oldRandomKeyList = resp.data.oldRandomKey;
                    that.logDataObject.newRandomKeyList = resp.data.newRandomKey;
                    that.logDataObject.oldKeySalt = resp.data.oldKeySalt;
                    that.logDataObject.newKeySalt = resp.data.newKeySalt;
                    that.logDataObject.peopelId = resp.data.peopelId;
                }).catch(err => {
                    // 失败执行
                    console.log(err);
                    // console.log('请求失败：' + err.status + ',' + err.statusText)
                })
            },
            verifyPasswordToLog(password) {
                let that = this;

                let oldPasswordMD5 = that.encrypt(
                    password,
                    that.logDataObject.oldKeySalt,
                    that.logDataObject.oldRandomKeyList
                );

                let newPasswordMD5 = that.encrypt(
                    password,
                    that.logDataObject.newKeySalt,
                    that.logDataObject.newRandomKeyList
                );

                Axios.post(
                    'http://xxx.com/xxx/xxx',
                    {
                        // 请求随机插入位与盐
                        code: 0,
                        msg: '用户登陆验证密码',
                        data: {
                            propleId: that.logDataObject.peopelId,
                            oldPasswordMD5: oldPasswordMD5,
                            newPasswordMD5: newPasswordMD5
                        },
                        isSuccess: false
                    }
                ).then(resp => {
                    // 承接接口回文数据
                    // {
                    //      "data": {
                    //         "token": 返回新生成的token，前端利用其更新客户端cookie,
                    //         "peopleId" : 用户id
                    //      },
                    //     "msg": "用户已完成登陆验证",
                    //     "code": 200,
                    //     "isSuccess": true
                    // }
                    //
                    // {
                    //     "data": {},
                    //     "msg": "用户登录异常",
                    //     "code": 501,
                    //     "isSuccess": false
                    // }
                    let respCode = resp.data.code;

                    if (respCode === 200) {
                        // 验证成功则更新 cookie ，失败则 要求重新登陆
                        let forumTokenCookie = {
                            token: resp.data.token,
                            peopleId: resp.data.peopleId
                        };
                        // 先删除现有 cookie 再生成新 cookie
                        this.$jsCookie.remove('forumTokenCookie', { path: 'forum' });
                        this.$jsCookie.set('forumTokenCookie', forumTokenCookie, { expires: 3, path: 'forum' });
                    } else if (respCode === 500) {
                        // 500 错误
                        console.log('500 错误');
                    } else if (respCode === 501) {
                        // 密码验证失败
                        this.$message.warning('密码验证失败，请重新登陆 Σ(っ °Д °;)っ');
                        // console.log('密码验证失败');
                    } else if (respCode === 502) {
                        // token 验证失败
                        console.log(
                            'token 验证失败，后台已记录此次通信记录，请勿尝试修改cookie文件进行非法访问，' +
                            '题必解保留对用户非法行为造成题必解损失的一切法律追究权利！'
                        );
                    } else if (respCode === 555) {
                        console.log('未知错误，请将该信息提交给官方进行问题纠错');
                    } else {
                        console.log('其他错误');
                    }


                }).catch(err => {
                    // 失败执行
                    console.log(err);
                    // console.log('请求失败：' + err.status + ',' + err.statusText)
                })
            },
            /* 公共函数 */
            encrypt(password, keySalt, randomKeyList) {
                // 拷贝盐
                let passwordAddSalt = JSON.parse(JSON.stringify(keySalt));

                let keyLength = randomKeyList.length;
                for(let num = 0; num < keyLength; num++) {
                    // 依据随机插入位数组，将密码的每一位覆盖到盐的对应随机插入位
                    passwordAddSalt.replace(randomKeyList[num], password[num]);
                }

                // 将插入到盐中的密码进行加密并获取密文并返回密文
                return MD5(passwordAddSalt);
            }
        },
        created() {
            // 轮播图自动轮播
            this.carouseTimer();

            // 用户密码依据随机插入位覆盖盐后MD5加密测试
            // let testPassword = 'kindSatan';
            // console.log('password: ' + testPassword);
            // this.keySalt = MD5('hello');
            // console.log('keySalt: ' + this.keySalt);
            // this.randomKeyList = [2, 8, 1, 15, 27, 14, 11, 4, 25];
            // console.log('randomKeyList: ' + this.randomKeyList);
            // console.log('passWordMD5: ' + this.encrypt(testPassword));

            // 为什么设置了这个 cookie 的 path 但是还是能在别的路径里访问到这个 cookie ?
            // 原因：因为 cookie path 被全部设为了 /forum, 而我测试的 path 全部基于 /forum 路径
            // 那么为什么会被全部设为 /forum 呢？我设的不是 /forum/registerLog 嘛？
            // 猜想：因为 Vue-router 采用 利用 history 或 hash 模式，其本身是基于对浏览器的一系列动作进行操作，
            // 并未涉及到新的 http 请求，所以本质还是基于 /forum 这个 http 路径，而 /forum 后续的 /registerLog 字段
            // 其实只是一个 history ( window.history ) 值 或是 hash ( HashHistory ) 值
            // 这些值只是用来指导 浏览器动作 的参数，而并非是类似于 /forum 一样的 http 路径值，这也就是为什么叫单页面应用的原因
            // let testCookie = {
            //     test: {
            //         name: 'testName',
            //         value: 'testValue'
            //     }
            // };
            // this.$jsCookie.set(testCookie.test.name + '3', testCookie.test.value, { expires: 3, path: 'forum/registerLog' });
            // this.$jsCookie.remove('testName', { path: 'forum/registerLog' });
            // console.log(this.$jsCookie.get());
            // console.log(undefined === this.$jsCookie.get('sdfsd'));
        }
    }
</script>

<style lang="scss" scoped>
    @import "../../../assets/stylesheets/animation.scss";

    .animationBackground {
        position: relative;
        z-index: 0;
        height: 100vh;
        width: 100vw;
        overflow-x: hidden;
        overflow-y: hidden;
        background-image: url("../../../assets/images/logBackground.jpg");
        background-size: 110% 110%;
        background-position: 10% 10%;
        background-repeat: no-repeat;
        animation: backgroundSwingUpAndDown 75s linear infinite;
        animation-play-state: paused;
        transition: all 0.4s linear;

        &:hover {
            animation-play-state: running;
        }

        &::after {
            position: absolute;
            z-index: 1;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
            content: '';
            background: rgba(255, 255, 255, 0.6);
        }
    }
    /* 登陆注册控制台 */
    .panelBox {
        position: relative;
        z-index: 2;
        top: 50%;
        left: 50%;
        width: 75vw;
        height: 75vh;
        border: 1px solid #999999;
        border-radius: 0.7em;
        box-shadow: 0 0 8px 4px rgba(0, 0, 0, 0.3);
        background: #fff;
        transform: translate(-50%, -50%);
    }
    .panelBox-carouselBox {
        position: relative;
        width: 47vw;
        height: calc(100% - 28vh);
        display: inline-block;
        margin: 14vh 1.5vw;
        overflow: hidden;
        vertical-align: top;

        &::before {
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 0;
            box-shadow: 0 0 200px 100px rgba(225, 225, 225, 0.85);
            content: '';
            z-index: 1;
        }

        &::after {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 0;
            box-shadow: 0 0 60px 30px rgba(225, 225, 225, 0.85);
            content: '';
            z-index: 1;
        }
    }
    .panelBox-carouselItem {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        transition: all 0.4s linear;

        img {
            position: relative;
            left: 50%;
            top: 50%;
            width: 100%;
            height: 100%;
            transform: translate(-50%, -50%);
        }
    }
    .panelBox-carouselActiveItem {
        opacity: 1;
    }
    .panelBox-contentBox {
        position: relative;
        width: calc(25vw - 2px);
        height: 100%;
        border-left: 1px solid #cccccc;
        display: inline-block;
        padding: 3vh 1vw;
        text-align: center;
        transition: all 0.4s linear;

        &:hover {
            border-left: 1px solid #666666;
        }
    }
    .panelBox-contentBox-title {
        font-size: 32px;
        font-weight: 300;
        text-indent: 0.5em;
        letter-spacing: 0.5em;
        cursor: default;
    }
    .panelBox-contentBox-userImgBox {
        position: relative;
        width: 11vh;
        height: 11vh;
        border: 1px solid rgba(200, 200, 200, 0.5);
        border-radius: 50%;
        margin: 3.5vh auto;
        background: rgba(175, 175, 175, 0.5);
        transition: all 0.4s linear;

        &:hover {
            background: rgba(175, 175, 175, 0.8);
        }

        img {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 9vh;
            height: 9vh;
            border-radius: 50%;
            transform: translate(-50%, -50%);
        }
    }
    .panelBox-contentBox-switchBox {
        position: relative;
        margin: 0 0 0.6vh;
        font-size: 24px;
    }
    .panelBox-contentBox-switchBox-separate {
        margin: 0 0.75em 0 0.5em;
        cursor: default;
    }
    .panelBox-contentBox-switchBox-item {
        letter-spacing: 0.25em;
        color: #aaaaaa;
        cursor: pointer;
        transition: all 0.4s linear;

        &:hover {
            color: #666666;
        }
    }
    .panelBox-contentBox-switchBox-activeItem {
        color: #333333;
    }
    .panelBox-contentBox-formBox {
        position: relative;
    }
    .panelBox-contentBox-formBox-item {
        position: absolute;
        padding: 0 0.6vw;
        left: 50%;
        transform: translateX(-50%);
        opacity: 0;
        z-index: -1;
        transition: all 0.4s linear;
    }
    .panelBox-contentBox-formBox-activeItem {
        opacity: 1;
        z-index: 0;
    }

    /* 独立拆分的组件样式 class */
    .input-textItem {
        position: relative;
        margin: 2.5vh 0;
        font-size: 16px;

        i {
            margin-right: 0.5em;
        }

        input {
            width: 15em;
            padding-right: 2.25em;
            padding-bottom: 0.3em;
            border: none;
            border-bottom: 1px solid #999999;
            outline: none;
            font-size: 14px;
            letter-spacing: 0.15em;
            transition: all 0.4s linear;

            &:hover {
                border-bottom: 1px solid #666666;
            }

            &:focus {
                border-bottom: 1px solid #333333;
            }
        }
    }
    .input-lookPassword {
        position: absolute;
        right: 0.25em;
        cursor: pointer;
        color: rgba(75, 75, 75, 0.5);
        transition: all 0.4s linear;

        &::after {
            position: absolute;
            top: 50%;
            left: 0;
            width: 105%;
            height: 2px;
            content: '';
            opacity: 0;
            transform: rotateZ(-60deg);
            background: rgba(75, 75, 75, 0.5);
            transition: all 0.4s linear;
        }

        &:hover {
            color: rgba(75, 75, 75, 1);
        }

        &:hover::after {
            background: rgba(75, 75, 75, 1);
        }
    }
    .input-onLookPassword {
        &::after {
            opacity: 1;
        }
    }
    .input-toolBox {
        font-size: 12px;
        letter-spacing: 0.2em;
        /*background: #e83e8c;*/
        overflow: hidden;
        clear: both;
    }
    .input-toolBox-forgetPassword {
        float: right;
        color: #999999;
        cursor: pointer;
        transition: all 0.4s linear;

        &:hover {
            color: #333333;
        }
    }
</style>
